package com.runfast.waimai.web.controller.Driver_controller;


//import com.fasterxml.jackson.annotation.JsonFormat;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.gxuc.runfast.bean.Shopper;
import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.RunfastAgentbusiness;
import com.runfast.paotui.dao.model.RunfastLoginRecord;
import com.runfast.paotui.dao.model.RunfastShopper;
import com.runfast.paotui.service.*;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.service.impl.RunfastGoodsSellRecordServiceImpl;
import com.runfast.waimai.util.*;
import io.netty.util.internal.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/driver/*")
public class DriverIndexController extends DriverBaseController {
	
	/***
	 * 首页信息 加载新订单 加载待取订单 送达 加载订单统计  ȡ取货
	 * 骑手是否有任务未完成 骑手上下班切换 签到  转单申请 骑手转单回复  转单详情  获取转单列表 定位信息 抢单
	 * **/
	@Resource
	RunfastBusinessService runfastBusinessService;
	@Resource
	OrderService orderService;
	@Resource
	private RunfastGoodsSellRecordService goodsSellRecordService;
	//RunfastGoodsSellRecord// 外卖商品订单
	@Resource
	private RunfastBusinessService businessService;
	//RunfastBusiness商家信息

	@Resource
	private RunFastSettingts runFastSettingts;
	//处理接单
	@Resource
	private RunfastShopperService shopperService;
	//骑手信息
	@Resource
	private RunfastGoodsSellOutStatusService goodsSellOutStatusService;
	// 外卖商品配送状态
	@Resource
	private RunfastTransorderService transOrderService;
	//转单信息
	
	@Resource
	private RunfastGoodsSellChildrenService goodsSellRecordChildrenService;
	/// 外卖商品订单记录子类
	
	@Resource
	private RunfastCreditlevelService creditLevelService;
	//信用等级管理
	
	@Resource
	private RunfastGoodsSellService goodsSellService;
	// 外卖商品订单记录
	
	@Resource
	private RunfastAccountrecordService associatorLevelService;
	// 表名：runfast_accountRecord 账号变动清单
	
	@Resource
	private RunfastCuserService cuserService;
	////用户信息
	
/*	@Resource
	private RunfastScroceSetService scroceSetService;
	*/
	
	@Resource
	private RunfastScorerecordService scoreRecordService;
	//用户积分记录
	/*@Resource
	private RunfastasAs associatorService;*/
	
	@Resource
	private RunfastDeliverCostService deliverCostService;
	@Resource
	private AmqpTemplate amqpTemplate; //队列推送
	@Resource
	RunfastAgentbusinessService runfastAgentbusinessService;

	
	protected static Logger LOG = LoggerFactory.getLogger(MsgPushUtils.class);
	
	/*@InitBinder//限定只有传参包含Application属性时才执行添加此操作
	public void initBinder(WebDataBinder binder) {
		//binder.setValidator(validator);
		//注册转换器
		binder.registerCustomEditor(Date.class, new MyCustomDateEditor());
	}*/
	
	/**
	 * 加载新订单
	 */
	@RequestMapping(value="loadneworders",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap loadneworders	(
			@RequestParam(value="page",required=false,defaultValue = "0")Integer page,
			@RequestParam(value="us",required=false,defaultValue = "1") Integer us,
			@RequestParam(value="pageSize",required=false,defaultValue = "10") Integer pageSize,
			String token ){ //新增骑手id
	    Integer page1=page*pageSize;
		ModelMap model = new ModelMap();
		if(super.getLoginShopper(token)!=null){//配送员信息不能为空
			RunfastShopper shopper   = shopperService.get(super.getLoginShopper(token).getId());
			Integer id1=super.getLoginShopper(token).getId();
			//Integer status=0;///转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
			List<RunfastTransorder> list1=  transOrderService.findByresShopperId(id1,0);////转单情况
			////转单信息
			model.put("transOrder", list1);

			PageBean<RunfastGoodsSellRecord> pageBean=null;

			Integer teamid=shopper.getTeamid();
			//获得分组ID

			if(shopper!=null&&shopper.getWorking()!=null&&shopper.getWorking()==1){


				 pageBean = goodsSellRecordService.getPageBean4Driver(pageSize,page1,1,super.getLoginShopper(token).getId(),shopper.getAgentId(),teamid);

				List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();

				if(pageBean.getTotalPage()>=pageSize){// 总页数
				for(RunfastGoodsSellRecord gr:pageBean.getData()){// 当前页数据
					if(gr!=null&pageBean.getTotalPage()>=page){
						gr=MyUtil.replaceTag(gr);
						Map<String, Object> map =new HashMap<String, Object>();
						System.out.println("----orderCode = " + gr.getOrdercode());
						//新版本是String类型，用Double.parseDouble转换
						map.put("distance", Math.round( Double.parseDouble(gr.getDistance())));
						map.put("id", gr.getId());
						map.put("content", gr.getContent());
						map.put("orderCode", gr.getOrdercode());
						map.put("showps", gr.getShowps());
						map.put("businessName", gr.getBusinessname());
						map.put("businessAddr", gr.getBusinessaddr());
						map.put("businessMobile", gr.getBusinessmobile());
						map.put("userAddress", gr.getUseraddress());
						map.put("address", gr.getAddress());
						map.put("userName", gr.getUsername());
						map.put("userMobile", gr.getUsermobile());
						map.put("createTime", gr.getCreatetime());
						map.put("payTime", gr.getPaytime());
						map.put("status", gr.getStatus());
						map.put("isCancel", gr.getIscancel());
						
						list.add(map);
						if(ComUtil.isEmpty(gr.getBusinessaddr()) && gr.getBusinessid()!=null){
							RunfastBusiness bus = businessService.findById(gr.getBusinessid());
							if(bus!=null){
								gr.setBusinessaddr(bus.getAddress());
								//goodsSellRecordService.update(gr);
							}
						}
						if(gr.getBusinessaddr()==null){
							gr.setBusinessaddr("");
						}
						
					}			
				}
					model.put("rows", list);
				}

				model.put("totalPage", pageBean.getTotalPage());
				model.put("currentPage", pageBean.getCurrentPage());

			//	model.put("rows",pageBean.getData());
				List<RunfastGoodsSellRecord> list2= goodsSellRecordService.findstatusnewmsg(page,pageSize,shopper.getAgentId());
                Integer count= goodsSellRecordService.findstatusnewmsgcount(page,pageSize,shopper.getAgentId());
                    //    findListPageBean(pageSize,page1,1,super.getLoginShopper(token).getId(),shopper.getAgentId(),teamid);
                model.put("allrow",count);
				model.put("rows",list2);
			}
		
		}
	// }
		return model;
	}
	/**
	 * 加载待取订单
	 */
	@RequestMapping(value="loadtakeorders",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap loadtakeorders	(
			@RequestParam(value="page",required=false,defaultValue = "0") Integer page,
			@RequestParam(value="pagesize",required=false,defaultValue = "10")Integer pageSize,String token){
	    Integer page1=page*pageSize;
		ModelMap model = new ModelMap();
		if(super.getLoginShopper(token)!=null){
			RunfastShopper shopper=shopperService.get(super.getLoginShopper(token).getId());
			Integer teamid=shopper.getTeamid();//骑手分组的ID

			//// 代理商Id：	分组ID ,骑手id 获得 外卖商品规格 信息
			PageBean<RunfastGoodsSellRecord> pageBean = goodsSellRecordService.getPageBean4Driver(pageSize,page1,2,super.getLoginShopper(token).getId(),shopper.getAgentId(),null);

						List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
						if(pageBean.getTotalPage()>=pageSize){ //总页数大于等于0
						for(RunfastGoodsSellRecord gr:pageBean.getData()){
							//输出外卖商品信息
				
				if(gr!=null&pageBean.getTotalPage()>=pageSize){//当外卖商品有内容时
		//			gr=MyUtil.replaceTag(gr); //更改里面的状态Stauts 为1
					Map<String, Object> map =new HashMap<String, Object>();
				Date disTime=gr.getDistime();
				Date createTime=gr.getCreatetime();//下单时间
				Date dates=new Date();
		//		long a=disTime.getMinutes()-createTime.getMinutes();
				if(disTime!=null&&createTime!=null){
	//				System.out.println(disTime.getTime());
//					System.out.println(createTime.getTime());
					LOG.error("", gr.getOrdercode());
				long b=disTime.getTime()-dates.getTime();//大约时间-下单时间
				long min=b/(60*1000);
			/*	long day = b / (1000 * 60 * 60 * 24);//相差天数
				long hour = (b / (60 * 60 * 1000) - day * 24);//小时
				long min = ((b / (60 * 1000)) - day * 24 * 60 - hour * 60);  //分
*/				    map.put("remainMin", min);
				}
				map.put("distance", Math.round(Double.parseDouble(gr.getDistance())));//外卖商品规格中提取配送距离
					map.put("id", gr.getId());// 外卖商品规格
					map.put("content", gr.getContent());////备注
					map.put("status", gr.getStatus());////订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
					map.put("orderCode", gr.getOrdercode());//订单号
					map.put("businessName", gr.getBusinessname());//商家名称
					map.put("businessAddr", gr.getBusinessaddr());//商家地址
					map.put("businessMobile", gr.getBusinessmobile());//商家电话
					map.put("userAddress", gr.getUseraddress());//用户地址
					map.put("shopperSign", gr.getShoppersign());//1已签到
					map.put("address", gr.getAddress());//门牌号
					map.put("userName", gr.getUsername());//用户名字
					map.put("userMobile", gr.getUsermobile());//用户手机号
					//没找到新版本的属性，先隐藏
					//map.put("showcode", gr.getShowcode());
					map.put("createTime", gr.getCreatetime());//用户下单时间
					map.put("disTime", gr.getDistime());//大约时间
					map.put("stype", gr.getStype());//临时字段（用于update数据库）
					map.put("payTime", gr.getPaytime());//付款时间
					map.put("isCancel", gr.getIscancel());//用户提出取消订单 1:用户提出 2:商家同意取消订单3:不同意取消订单

					list.add(map);
					if(ComUtil.isEmpty(gr.getBusinessaddr()) && gr.getBusinessid()!=null){
						RunfastBusiness bus = businessService.findById(gr.getBusinessid());
						if(bus!=null){
							gr.setBusinessaddr(bus.getAddress());//商家地址
							//goodsSellRecordService.update(gr);
						}
					}
					if(gr.getBusinessaddr()==null){
						gr.setBusinessaddr("");
					}
				}	
			}
			model.put("rows", list);
			}
			model.put("totalPage", pageBean.getTotalPage());
			model.put("currentPage", pageBean.getCurrentPage());
//			model.put("allrow", pageBean.getAllRow());
//			List<RunfastGoodsSellRecord> list2= goodsSellRecordService.findListPageBean(pageSize,page1,2,super.getLoginShopper(token).getId(),shopper.getAgentId(),teamid);
//			model.put("rows",list2);
			DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date=new Date();

			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(date);
			rightNow.add(Calendar.HOUR,-1);

			Date dt1=rightNow.getTime();
            List<RunfastGoodsSellRecord> list2= goodsSellRecordService.findstatus(2,page1,pageSize,shopper.getAgentId(),shopper.getId(),dt1);
            Integer count= goodsSellRecordService.findstatuscount(null ,page1,pageSize,shopper.getAgentId(),shopper.getId(),dt1);
            //    findListPageBean(pageSize,page1,1,super.getLoginShopper(token).getId(),shopper.getAgentId(),teamid);
            model.put("allrow",count);
            model.put("rows",list2);
	//		model.put("rows",pageBean.getData());

			}else {
			model.put("msg","没有待取的定单");
		//	model.put("pageBean",pageBean);
		}
		
		return model;
	}
	/**
	 *加载待送订单
	 */
	@RequestMapping(value="loadsendorders",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap loadsendorders	(
		 	Integer page,
			Integer pageSize,String token){
		ModelMap model = new ModelMap();
		if(super.getLoginShopper(token)!=null){//
			RunfastShopper shopper=super.getLoginShopper(token);
		//	Integer teamid=shopper.getTeamid();
//			super.getLoginShopper(token).getId(),shopper.getAgentId(), status
//			goodsSellRecordService.find


		PageBean<RunfastGoodsSellRecord> pageBean = goodsSellRecordService.getPageBean4Driver(pageSize,page,3,super.getLoginShopper(token).getId(),shopper.getAgentId(),null);
	//	Integer count=goodsSellRecordService.f
			List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
			if(pageBean.getTotalPage()>=pageSize){
			for(RunfastGoodsSellRecord gr:pageBean.getData()){
				
				if(gr!=null){
		//			gr=MyUtil.replaceTag(gr);
					Map<String, Object> map =new HashMap<String, Object>();
					Date disTime=gr.getDistime();
					Date createTime=gr.getCreatetime();
					Date newdate=new Date();
	//				System.out.print(disTime);
	//				System.out.println(disTime.getTime());
	//				System.out.println(createTime.getTime());
			//		long a=disTime.getMinutes()-createTime.getMinutes();
					if(disTime!=null&&createTime!=null){
					long b=disTime.getTime()-newdate.getTime();
					long min=b/(60*1000);
					map.put("remainMin", min);
					
					}
					map.put("distance", Math.round(Double.parseDouble(gr.getDistance())));// 配送距离
					map.put("id", gr.getId());
					map.put("content", gr.getContent());
					map.put("shopperSign", gr.getShoppersign());//已签到
					map.put("orderCode", gr.getOrdercode());//定单号
					map.put("businessName", gr.getBusinessname());//商家名称
					map.put("businessAddr", gr.getBusinessaddr());//商家地址
					map.put("businessMobile", gr.getBusinessmobile());//商家手机号
					map.put("userAddress", gr.getUseraddress());//用户地址
					map.put("address", gr.getAddress());//门牌号
					map.put("userName", gr.getUsername());//用户名称
					map.put("userMobile", gr.getUsermobile());//用户手机号
					map.put("createTime", gr.getCreatetime());//用户下单时间
					//没找到该属性
			//		map.put("showcode", gr.getShowcode());
					map.put("disTime", gr.getDistime());
					map.put("status", gr.getStatus());
					map.put("isCancel", gr.getIscancel());
					map.put("payTime", gr.getPaytime());
					list.add(map);
					if(ComUtil.isEmpty(gr.getBusinessaddr()) && gr.getBusinessid()!=null){
						RunfastBusiness bus = businessService.findById(gr.getBusinessid());
						if(bus!=null){
							gr.setBusinessaddr(bus.getAddress());
							//goodsSellRecordService.update(gr);
						}
					}
					if(gr.getBusinessaddr()==null){
						gr.setBusinessaddr("");
					}
					
				}
				
			}
			model.put("rows",list);	
			}
			model.put("totalPage", pageBean.getTotalPage());
			model.put("currentPage", pageBean.getCurrentPage());
			model.put("allrow", pageBean.getAllRow());
			List<RunfastGoodsSellRecord> list2= goodsSellRecordService.findListPageBean(pageSize,page,5,super.getLoginShopper(token).getId(),shopper.getAgentId(),null);
			model.put("rows",list2);
	//		model.put("rows",pageBean.getData());
		}else {
			model.put("msg","没有待加载的定单");
		}
	return model;
	}
	/**
	 * 加载订单统计
	 */

	@RequestMapping(value="loadstatrders",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap loadstatrders	( @RequestParam(value = "us",required = false,defaultValue = "1") Integer us,String token,
                                                     @RequestParam(value = "page",required = false,defaultValue = "0")Integer page,
                                                     @RequestParam(value = "pagesize",required = false,defaultValue = "10")Integer pagesize){
	    Integer page1=page*pagesize;
		ModelMap model = new ModelMap();

	//	Integer cout5=  goodsSellRecordService.findstatusnewmsgcount(page1,pagesize,39);

		if(super.getLoginShopper(token)!=null){
			RunfastShopper runfastShopper=super.getLoginShopper(token);
			Integer teamid=runfastShopper.getTeamid();//通过骑手信息获得分组ID

			DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date=new Date();

			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(date);
			rightNow.add(Calendar.HOUR,+1);

			Date dt1=rightNow.getTime();
			System.out.println(runfastShopper+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
          Integer cout=  goodsSellRecordService.findstatusnewmsgcount(page1,pagesize,runfastShopper.getAgentId());
			RunfastAgentbusiness runfastAgentbusiness=runfastAgentbusinessService.findByid(runfastShopper.getAgentId());
			if(runfastAgentbusiness.getOrderMode()!=2){
				model.put("allrow_1", cout);//新任务
			}else { 	model.put("allrow_1", 0);}


            Integer cout2=  goodsSellRecordService.findstatuscount(runfastShopper.getStatus(),page1 ,pagesize,runfastShopper.getAgentId(),runfastShopper.getId(),dt1);
            		model.put("allrow_2", cout2);//骑手抢单成功后，进入待取货,还有状态为1的时候，shopper生成，待取货的单

            Integer cout3=  goodsSellRecordService.findCount(pagesize,page ,5,runfastShopper.getId(),runfastShopper.getAgentId(),null);
           			model.put("allrow_3", cout3);//骑手从商家取完单 ，待送达单

			//Integer cout4=goodsSellRecordService.findCount(pagesize,page ,9,runfastShopper.getId(),runfastShopper.getAgentId(),null);
			Integer cout4=goodsSellRecordService.findShopperAndStatusErroCount(runfastShopper.getId());
					model.put("allrow_4", cout4);//异常单

			Integer cout5=goodsSellRecordService.findBookTimecount(runfastShopper.getId(),dt1,runfastShopper.getAgentId());

			model.put("allrow_5",cout5); //预定单

		}
		return model;
	}

	/**
	 * 送达
	 */
	@RequestMapping(value="orderarrived",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap orderarrived( Integer id,String token){
		//id为定单id
		ModelMap model = new ModelMap();

		if(super.getLoginShopper(token)!=null&&id!=null){

			RunfastShopper shopper=shopperService.get(super.getLoginShopper(token).getId());
			RunfastGoodsSellRecord gr = goodsSellRecordService.findByShopperIdAndId(super.getLoginShopper(token).getId(),id);
			RunfastTransorder t = transOrderService.findByorderCode1(gr.getOrdercode());//转单情况
				if(t!=null&&t.getStatus()==0){
					System.out.println("看看&&&&&&&&&&&&&&&&&&&&&");
					model.put("success",false);
					model.put("msg","转单申请中的定单，得先取消申请才行！");
				}else {
					if (gr != null && gr.getStatus() != null && gr.getStatus() == 5) {
						//订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
						gr.setStatus(8);//商品送达
						gr.setIsreceive(1);//设定为已收货
						gr.setStatus(8);//订单完成
						gr.setStatstr("订单完成");//订单完成
						gr.setReadytime(new Date());//订单完成时间

						goodsSellRecordService.updateByPrimaryKey(gr);///更新数据外卖商品订单记录
						goodsSellService.updateSalesnum(gr);//// 更新外卖商品
						goodsSellRecordChildrenService.updateFindByPid(gr.getId(), 8);//执行定单更新和返回INT

						//订单状态操作记录
						RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
						goodsSellOutStatus.setBusinessid(gr.getBusinessid());//设置商家ID
						goodsSellOutStatus.setBusinessname(gr.getBusinessname());//设置商家名字
						goodsSellOutStatus.setCreatetime(new Date());//设置订单时间
						goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());//设置订单号
						goodsSellOutStatus.setGoodssellrecordid(gr.getId());////商品订单ID
						goodsSellOutStatus.setOperationid(shopper.getId());//设置骑手ID
						goodsSellOutStatus.setOperationname(shopper.getName());//设置骑手姓名
						goodsSellOutStatus.setSort(8);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
						goodsSellOutStatus.setStatstr("订单完成");
						goodsSellOutStatus.setType(2);///操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
						goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
					/*RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);

				  if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(8))||goodsSellOut.getSort()==null){
					  goodsSellOutStatusService.insertSelective(goodsSellOutStatus);

				  }*/
						//积分
						com.runfast.paotui.dao.model.RunfastCuser cuser = cuserService.get(gr.getUserid());

						HashMap<String, String> params = new HashMap<>();
						params.put("orderCode", gr.getOrdercode());
						MsgPushUtils.pushToUser(10, params, "送达提醒", "您的订单:" + gr.getOrdercode() + "已经送达", cuser.getAlias());
						//会员等级一堆错误，先注解掉，没有实体类等一切信息
						if (cuser != null)/*{
						RunfastScorerecord sr=new RunfastScorerecord();

						RunfastScroceSet t=scroceSetService.findBy();
						sr.setCardnumber(gr.getOrdercode());
						sr.setCid(cuser.getId());
						sr.setCreatetime(new Date());
						sr.setMobile(cuser.getMobile());
						sr.setMonetary(gr.getTotalpay());
						sr.setName(cuser.getName());
						sr.setScore(gr.getTotalpay().doubleValue());
						if(t!=null){
							sr.setScore(gr.getTotalpay().multiply(BigDecimal.valueOf(t.getConsumexs())).doubleValue());
						}
						sr.setType(2);
						scoreRecordService.insert(sr);
						if(cuser.getScore()!=null){
							cuser.setScore(sr.getScore()+cuser.getScore());
						}else{
							cuser.setScore(sr.getScore());
						}
						cuserService.update(cuser);
					//修改会员等级
						if(ComUtil.isEmpty(cuser.getCard())){
							//会员
							Associator ass=associatorService.findByCardNumber(cuser.getCard());
							if(ass!=null){
								if(ass.getMonetary()!=null){
									ass.setMonetary(ass.getMonetary().add(gr.getTotalpay()));
								}else{
									ass.setMonetary(gr.getTotalpay());
								}
								AssociatorLevel al=associatorLevelService.getLevel(ass.getMonetary());
								if(al!=null){
									ass.setLevelId(al.getId());
									ass.setLevelName(al.getName());
									ass.setSort(al.getSort());
									associatorService.update(ass);
								}
							}
						}
				  }*/


							model.put("msg", "配送成功!");
						model.put("success", true);
						//	String str=JSON.toJSONString(gr);
						//	this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列

						amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
					}
				}
		}else{model.put("msg", "系统错误或者是转单定单一直处于申请状态中，是不能点送达的");
			model.put("success", false); }

		return model;
	}
	/**
	 * ȡ取货
	 */
	@RequestMapping(value="ordertake",method=RequestMethod.POST)//验证֤
	public @ResponseBody ModelMap ordertake( Integer id,String token){
		ModelMap model = new ModelMap();

		System.out.println(token);
		if(super.getLoginShopper(token)!=null&&id!=null){
			RunfastShopper runfastShopper=shopperService.get(super.getLoginShopper(token).getId());

		RunfastGoodsSellRecord gr = goodsSellRecordService.findByShopperIdAndOrderCode(super.getLoginShopper(token).getId(),id);//通过骑手ID ,定单号获得外卖商品规格
			// 外卖商品订单

			if(!gr.getShopperid().equals(super.getLoginShopper(token).getId())){

				 model.put("success",false);
				 model.put("msg","该订单为其他骑手订单");
			}

				if(gr.getShoppersign()==null&&(gr.getStatus()==2||gr.getStatus()==3)&&gr.getShopperid()!=null){

				model.put("msg","骑手还没签到！");
				model.put("success", false);
				}else {


					if(gr.getShoppersign()==null){

						model.put("msg", "骑手还没有签到");
						model.put("success", false);
					}else {


				if(gr!=null&&gr.getStatus()!=null&&gr.getStatus()>=3&&gr.getStatus()<=4&&gr.getShoppersign()==1){
					////订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
					if(gr.getIscancel()!=null&&gr.getIscancel()==1){
						//用户申请取消订单

						model.put("success",false);
						model.put("msg","用户申请取消该订单，请等待商家审核!");
					}else{
				/*		if(gr.getStatus()==3){
							RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
							//  外卖商品配送状态
							goodsSellOutStatus.setBusinessid(gr.getBusinessid());//商家ID
							goodsSellOutStatus.setBusinessname(gr.getBusinessname());//商家 名称
							goodsSellOutStatus.setCreatetime(new Date());//状态时间
							goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());//设置定单号
							goodsSellOutStatus.setGoodssellrecordid(gr.getId());//设置外卖商品id
							goodsSellOutStatus.setSort(5);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
							goodsSellOutStatus.setType(2);//  操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
							goodsSellOutStatus.setStatstr("商品配送");
							goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
							*//*RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 3);
							if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(4))){
								////   sort 订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达

							}*//*
						}*/
						//
						//重新计算送达时间
//						  DeliverCost deli = null;
//						  Integer agent = gr.getAgentId();
//						  double distance =  gr.getDistance();
//						  if(gr.getBusinessId()!=null){
//							if (agent != null) {
//								if(deli==null){
//									deli = deliverCostService.findByAgent(agent);
//								}
//								if (deli == null) {
//									deli = deliverCostService.findBy();
//								}
//								if (deli != null) {
//									Double speed =  deli.getSpeed();
//									if(speed==null){
//										speed=1.0;
//									}
//									speed = speed /100;
//									int times = (int) (distance * speed);
//									if(times<15){
//										times=15;
//									}
//									Calendar calendar = Calendar.getInstance();
//									calendar.setTime(new Date());
//									calendar.add(Calendar.MINUTE, times);
//									gr.setDisTime(calendar.getTime());
//
//								}
//							}
//						 }

						//订单状态操作记录
						RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
						goodsSellOutStatus.setBusinessid(gr.getBusinessid());
						goodsSellOutStatus.setBusinessname(gr.getBusinessname());
						goodsSellOutStatus.setCreatetime(new Date());
						goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());
						goodsSellOutStatus.setGoodssellrecordid(gr.getId());
						goodsSellOutStatus.setOperationid(super.getLoginShopper(token).getId());
						goodsSellOutStatus.setOperationname(runfastShopper.getName());
						goodsSellOutStatus.setSort(5);
						goodsSellOutStatus.setStatstr("骑手正在送货");
						goodsSellOutStatus.setType(2);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
						goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
						gr.setStatus(5);
						gr.setStatstr("骑手正在送货");
						goodsSellRecordService.update(gr);
//						RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);
//						if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(5))){
//							goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
//						}
						//String str=JSON.toJSONString(gr);
					//	this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
						amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
						model.put("success",true);
						model.put("msg","取货成功");
					}

				}else{

						if(gr.getShoppersign()!=1&&(gr.getStatus()==3||gr.getStatus()==1)) {
							model.put("msg", "骑手没有签到");
							model.put("success", false);
						}else {
							model.put("msg", "商家没接单");
							model.put("success", true);
						}


				}}
			}

			
		}

		return model;
	}
	/**
	 * 抢单
	 */
	@RequestMapping(value="orderfight",method=RequestMethod.POST)///验证
	public @ResponseBody ModelMap orderfight(@RequestParam(value="id",required=false) Integer id,String token){
		//定单id
		ModelMap model = new ModelMap();
	//	String msg ="参数错误";
		boolean isSuccess = false;
		System.out.println(id+"aaaaaaaaa");
		System.out.println(token+"aaaaaaaaabbbb");
		RunfastShopper shopper=super.getLoginShopper(token);
		if(shopper!=null&&id!=null&&shopper.getWorking()==1){


			int size=0;
			Integer num=super.getLoginShopper(token).getDistributionmun();//  配送最大数量默认为5
	//		Integer num=5;
			if(num==null){
				num=5;
			}
		//	List<Order>list1=orderService.findByShopperid(super.getLoginShopper(token).getId());
			List<Order> list1 = orderService.findByShopperidAndStatusSize(super.getLoginShopper(token).getId());
			List<RunfastGoodsSellRecord> glist= goodsSellRecordService.findByShopperIdAndStrutsSize(super.getLoginShopper(token).getId());
		//	List<RunfastGoodsSellRecord> glist=  goodsSellRecordService.findByShopperAndSize(super.getLoginShopper(token).getId());//通过骑手ID 获得手上订单信息集合,status等于1和2

			 // 外卖商品订单
			if(glist!=null){
				size=glist.size(); //获得骑手手上的订单的数量
			}
			if((size+list1.size())<(num+1)){
				//(num+1) ，测试用20
				//小于NUM+1，说明还可以接单
				if(!runFastSettingts.hasTakeThatOrderId(id)){
					// * 判断是否有人正在执行该订单的接单操作定单
					runFastSettingts.addTakeThatOrderId(id);//添加正在接单操作的订单id
					System.out.println("runFastSettingts.addTakeThatOrderId(id)");
					
					RunfastGoodsSellRecord gr = goodsSellRecordService.get(id);//订单ID 获得订单信息
					if(gr!=null&&gr.getShopperid()==null&&gr.getStatus()!=null&&(gr.getStatus()==2||gr.getStatus()==1)){
						//1：客户已付款  2：商家接单
						gr.setShopperid(super.getLoginShopper(token).getId());//设置骑手id
						gr.setShopper(shopper.getName());//设置骑手名字
						gr.setShoppermobile(shopper.getMunber());//设置骑手 的手机号
						gr.setCreatetime(new Date());
						if(gr.getBookTime()==null){
							gr.setBookTime(gr.getCreatetime());}
				//			goodsSellRecordService.insertSelective(gr);}

						RunfastCreditlevel c=null;// // 信用等级管理
						if(shopper.getCreditLevelid()!=null){
							System.out.println(shopper.getCreditLevelid()+"信誉等级id*************");
							c=creditLevelService.get(shopper.getCreditLevelid());//查看信誉等级情况
							System.out.println(c+"信誉等级信息1*************");
						}else{
							List<RunfastCreditlevel> list=  creditLevelService.findAll();//  信用等级管理

							if(list!=null&&list.size()>0){
								c=list.get(0);  //根据最少的信誉等级计算的
								System.out.println(c+"信誉等级信息2*************");
							}
						}
						
						if(c!=null){
							System.out.println("信誉等级信息3*************"+c);
							BigDecimal shopperMoney=BigDecimal.valueOf(0);
							if(c.getStarttimeday()!=null && c.getEndtimeday()!=null){
								//白班开始时间              //白班结束时间
								Calendar calendar = Calendar.getInstance();
								int hour = calendar.get(Calendar.HOUR_OF_DAY);
									calendar.setTime(c.getStarttimeday());
								int startTime1 = calendar.get(Calendar.HOUR_OF_DAY);
								calendar.setTime(c.getEndtimeday());
								int endTime1 = calendar.get(Calendar.HOUR_OF_DAY);
								if(MyUtil.inTime(c.getStarttimeday(), c.getEndtimeday(), new Date())){
									//符合第一时段配送费
									shopperMoney=c.getCommissionday();  //白班每笔订单提成
									
								}else{
									shopperMoney=c.getCommissionnight();  ////晚班每笔订单提成
								}
								if(shopperMoney==null){
									shopperMoney=BigDecimal.valueOf(0);
								}
								if(gr.getDistance()!=null){
									//// 配送距离   ;//超出多少公里后额外加钱 //额外每公里加多少钱
									if(gr.getDistance()!=null&&c.getDistan()!=null&&c.getPrice()!=null){//distan超出多少公里后额外加钱
										Double distan=c.getDistan(); //超出多少公里后额外加钱
										if(Double.parseDouble(gr.getDistance())>distan*1000){
											//当超出了范围后，计算超出的费用
											 double ss =  Double.parseDouble(gr.getDistance()) - distan*1000;
											       ss = ss /1000;
											       if(ss%1!=0){
											    	    ss=  ss+1; 
											       }
											  int sd = (int)ss;
											  BigDecimal priceshopper = c.getPrice().multiply(BigDecimal.valueOf(sd));  //额外每公里加多少钱
										      shopperMoney=shopperMoney.add(priceshopper);
										      if(c.getMaxprice()!=null){
										    	if(shopperMoney.compareTo(c.getMaxprice())==1){
										    		shopperMoney = c.getMaxprice();
										    	}  
										     }
										}
									 }
								}
								gr.setShoppermoney(shopperMoney);
							//	gr.setCommisson(shopperMoney);
							}
						}


						//订单状态操作记录
						  RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
						  goodsSellOutStatus.setBusinessid(gr.getBusinessid());
						  goodsSellOutStatus.setBusinessname(gr.getBusinessname());
						  goodsSellOutStatus.setCreatetime(new Date());
						  goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());
						  goodsSellOutStatus.setGoodssellrecordid(gr.getId());
						  goodsSellOutStatus.setOperationid(id);
						  goodsSellOutStatus.setOperationname(shopper.getName());
						  goodsSellOutStatus.setSort(3);
						  if(gr.getStatus()==1){
							  gr.setStype(1);
							  goodsSellOutStatus.setStatstr("骑手已接单，等待商家接单");
							  System.out.println("111111111111111111111111111111111111111111111111111111111");
						  }else if(gr.getStatus()==2&&gr.getShopper()==null){
							  gr.setStatus(3);//骑手接单
							  gr.setStatstr("骑手已接单");
							  gr.setShoppermobile(shopper.getMunber());
							  gr.setShopper(shopper.getName());
							  gr.setShopperid(shopper.getId());
							  gr.setCreatetime(new Date());
							  goodsSellRecordService.update(gr);//将骑手信息更新到定单，应该算是抢单成功
							  goodsSellOutStatus.setStatstr("骑手赶往商家中");

						  }else if(gr.getStatus()==2&&gr.getShopper()!=null){
							  goodsSellOutStatus.setStatstr("骑手已接单");
							  goodsSellOutStatus.setSort(3);
						  	gr.setStatus(3);
							  gr.setStatstr("骑手已接单");
						  }
					  		goodsSellOutStatus.setType(2);;//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

						model.put("msg", "抢单成功");
						model.put("success",true);
						  RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 1);
						  if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(3))){
						  	////sort    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
							  goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
						  }	 
						  RunfastGoodsSellRecord grtemp = goodsSellRecordService.get(id);// 外卖商品规格
						  if(grtemp != null &&  grtemp.getShopperid()==null)
						  {

						//	  gr.setStatus(1);

							  goodsSellRecordService.update(gr);//将骑手信息更新到定单，应该算是抢单成功
							  System.out.println(gr.getShoppermoney()+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
						//	  String str=JSON.toJSONString(gr);
						//	  System.out.println(str+"*************************************************************");
							//  this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
							  amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
							  model.put("success",true);
							  model.put("msg","抢单成功");
						  }else{
							//  msg="订单已经被抢走1";
							  model.put("msg", "订单已经被抢走了");
						  }
						isSuccess = true;
					}else{
						String	msg = "该订单已被抢走了啊!";
						model.put("msg", msg);
					}
					runFastSettingts.removeTakeThatOrderId(id);//删除正在接单操作的订单id
				}else{
					System.out.println(!runFastSettingts.hasTakeThatOrderId(id));
					String	msg = "该订单已被抢走了哇!";
					model.put("msg", msg);
				}
			}else{
				String	msg = "未完成订单已达上限，请先完成手上订单!";
				model.put("msg", msg);
				model.put("success",false);
			}
			}

		return model;
	}
	/**
	 * 定位信息
	 */
	//@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
	@RequestMapping(value="uploadloc",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap uploadloc	(
		//	@RequestParam(value="userName",required=false) String userName,
			@RequestParam(value="lat",required=false) String lat,//经度
			@RequestParam(value="lng",required=false) String lng,//纬度
			@RequestParam(value="bdchannelId",required=false,defaultValue = "1") String bdchannelId,
			@RequestParam(value="bduserId",required=false,defaultValue = "1") String bduserId,
			@RequestParam(value="bptype",required=false,defaultValue="0") Integer bptype,
			String token //骑手id
		//	 HttpServletResponse response
			) throws IOException {
		ModelMap model = new ModelMap();
	//	boolean isSuccess = false;


			long current=System.currentTimeMillis();//当前时间毫秒数
			long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
			long twelve=zero+24*60*60*1000-1;//今天23点59分59秒的毫秒数
			long yesterday=System.currentTimeMillis()-24*60*60*1000;//昨天的这一时间的毫秒数
			System.out.println(new Timestamp(current));//当前时间
			System.out.println(new Timestamp(yesterday));//昨天这一时间点
			System.out.println(new Timestamp(zero));//今天零点零分零秒
			System.out.println(new Timestamp(twelve));//今天23点59分59秒
		Date date1=new Timestamp(zero);
		Date date2=new Timestamp(twelve);

            boolean flag=true;

            RunfastShopper shopper=super.getLoginShopper(token);

			    //当订单不完成时，不停刷新
                if(shopper!=null){

                        try{

//					shopper.setLatitude(lat);
//					shopper.setLongitude(lng);

//						List<RunfastGoodsSellRecord> list=  goodsSellRecordService.findById(shopper.getId());//查询骑手手上的订单信息集合
//						if(list!=null&&list.size()>0){//手上有订单时
//							model.put("isorder", "1");//回复1，说明手上还有订单
//						}else{
//							model.put("isorder", "0"); //说明手上已经没有订单了
//						}
						shopper.setLatitude(lat);//设置经度
						shopper.setLongitude(lng);//设置纬度
						if(ComUtil.isEmpty(shopper.getBdchannelId())&&ComUtil.isEmpty(shopper.getBduserId())){
							//百度推送信息
							if(!ComUtil.isEmpty(bdchannelId) && !ComUtil.isEmpty(bduserId)){
								shopper.setBptype(bptype);//0或空  Android用户  1 ios用户
								shopper.setBdchannelId(bdchannelId);//推送渠道ID
								shopper.setBduserId(bduserId);//推送用户ID
							}
						}
							shopperService.update(shopper);//只更新经度和纬度
							System.out.println(shopper.getLongitude()+"经度"+shopper.getLatitude());
							RunfastShopper shopper1=super.getLoginShopper(token);
							System.out.println(shopper1.getLongitude()+"经度#################"+shopper1.getLatitude()+"骑手id"+shopper1.getId());
							amqpTemplate.convertAndSend("shopper_exchange", "", JSON.toJSONString(shopper1));
                        model.put("success",true);
                        model.put("msg","经度纬度保存成功");


			//        out.print(super.getLoginShopper(token));
			//		out.print("id=shopper <input type='hidden' value='shopper' name='id'>");
//					可以这样传，在前台的JS中使用下面的语句获取：
//					document.getElementById('id').value

//					out.flush();
//					Thread.sleep(5000);//5秒存刷新一次
           //      String str=JSON.toJSONString(shopper);
		//					System.out.println(shopper.getLatitude()+"纬度&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+shopper.getLongitude());
			//				System.out.println(str+"更新后的结果");
			//		this.rabbitTemplate.convertAndSend("hellowo", str); //保存在队列

//                    if(shopper.getStatus()==8){
//                        model.put("sucess",true);
//                        model.put("msg","订单完成");
//                        flag=false;
//                        out.close();
//                    }
     //              System.out.println(str);
				}catch (Exception e){
					e.printStackTrace();
				}

                    model.put("success",true);
			}





		return model;
	}
	/**
	 *  获取转单列表
	 */
	@RequestMapping(value="sing",method=RequestMethod.POST)//验证
	public  @ResponseBody ModelMap shopper(@RequestParam(value="orderCode",required=false) String orderCode,//id
			@RequestParam(value="lat",required=false) Double lat,//骑手经度
			@RequestParam(value="lng",required=false) Double lng,///骑手纬度
			@RequestParam(value="address",required=false) String address,///商家地址
			@RequestParam(value="oid",required=false) Integer oid,//0没订单 1有订单
				String token //骑手id
	){
		ModelMap model= new ModelMap();
		Double distance=5000.00;//米

		RunfastShopper runfastShopper=super.getLoginShopper(token);

		if(runfastShopper!=null){

	//		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
			RunfastGoodsSellRecord gr =goodsSellRecordService.findByOrderCode(orderCode);//外卖商品规格信息
		if(gr == null)
		{   model.put("error", "目前手上在没有定单");
			model.put("success",false);
			return model;
		}
	List<RunfastShopper> slist=shopperService.findBuAgentId(gr.getAgentid(), gr.getTeamid());

		if(slist == null || slist.isEmpty())
		{

			model.put("error", "shopper list is null");
			model.put("success",false);
			return model;
		}
		List<Map<String,Object>> MapList = new ArrayList<Map<String,Object>>();

		 if(slist!=null&&slist.size()>0){
		for(RunfastShopper sp:slist){
			System.out.println(slist+"###############################");
//			System.out.println(sp.getName());
			Map<String,Object> returnMap =new HashMap<String,Object>();
			if(sp!=null && sp.getLatitude() != null && sp.getLongitude() != null&&sp.getId()!=super.getLoginShopper(token).getId()&&!sp.getUserName().equals(runfastShopper.getUserName())){
			   Double lng1= Double.parseDouble(sp.getLongitude());
			   Double lat1=Double.parseDouble(sp.getLatitude());
				System.out.println(sp.getLatitude()+"***************************");
				System.out.println(sp.getLongitude()+"***************************");
			   if(lat!=null&&lng!=null&&lat1!=null&&lng1!=null){
			   Double dis=MyUtil.getDistance(lat1, lng1, lat, lng);// // 返回单位是米
				   System.out.println(lat1 +"lat1$$$$$$ "+lng1+" lng1 &&&&&&&& "+lat+"lat&&&& "+lng+"lng******");
	//			   Double a1= MyUtil.getDistance(30.578786,114.354899,30.351468,114.351464);
//				   System.out.println(a1+"aa1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
	//			   Double a= MyUtil.getDistance(30.578786,114.354901,30.57882,114.35494);
	//			   System.out.println(a+"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
			//	   dis1= dis * MyUtil. EARTH_RADIUS;
			//	   Long dis1=Long.valueOf(String.valueOf(dis));
			//  dis= Math.round(dis * 10000) / 10000;
	//			   System.out.println(dis+"dis123333333333333333333333333333333333333333333333333333333333334");

			   if(dis<distance){
				  Map<String, Object> map=MyUtil.getAddress(lng1, lat1);//根据经纬度获取百度位置
				  String name= sp.getName();///名称
	//			   System.out.println("123333333333333333333333333333333333333333333333333333333333334");
		//		  PageBean<RunfastGoodsSellRecord> pageBean = goodsSellRecordService.getPageBean4Driver(10,0,2,sp.getId(),sp.getAgentId(),sp.getTeamid());//待取货订单
		//		  PageBean<RunfastGoodsSellRecord> pageBean1 = goodsSellRecordService.getPageBean4Driver(10,0,3,sp.getId(),sp.getAgentId(),sp.getTeamid());//待送达订单
				   DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				   Date date=new Date();

				   Calendar rightNow = Calendar.getInstance();
				   rightNow.setTime(date);
				   rightNow.add(Calendar.HOUR,-1);

				   Date dt1=rightNow.getTime();
				   List<RunfastGoodsSellRecord> goodsSellRecord = goodsSellRecordService.findstatus(null, 0, 10, sp.getAgentId(),sp.getId(),dt1);
				   List<RunfastGoodsSellRecord> goodsSellRecord1 = goodsSellRecordService.findListPageBean(10, 0, 5, super.getLoginShopper(token).getId(), sp.getAgentId(), null);
				   //   Double a = 3.1415926;
				   DecimalFormat obj = new DecimalFormat(".0");  // 保留1位小数

//				   System.out.println("disMine############"+obj .format(MyUtil.getDistance(lat, lng, Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));///两个骑手之间的距离
//				   System.out.println("disShop############"+obj.format( MyUtil.getDistance( Double.parseDouble(gr.getBusinessaddresslat()),  Double.parseDouble(gr.getBusinessaddresslng()), Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));
//				   System.out.println("disuser################"+obj.format( MyUtil.getDistance( Double.parseDouble(gr.getUseraddresslat()),  Double.parseDouble(gr.getUseraddresslng()), Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));
//			//	 returnMap.clear();
				  returnMap.put("number", sp.getMunber());//骑手电话
				  returnMap.put("disMine",obj .format(MyUtil.getDistance(lat, lng, Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));///两个骑手之间的距离
				  returnMap.put("disShop",obj.format( MyUtil.getDistance( Double.parseDouble(gr.getBusinessaddresslat()),  Double.parseDouble(gr.getBusinessaddresslng()), Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));//商户与骑手之间的距离
				  returnMap.put("disUser",obj.format( MyUtil.getDistance( Double.parseDouble(gr.getUseraddresslat()),  Double.parseDouble(gr.getUseraddresslng()), Double.parseDouble(sp.getLatitude()), Double.parseDouble(sp.getLongitude()))));//用户与骑手之间的距离
				  returnMap.put("id", sp.getId());//骑手ID
			//	  returnMap.put("orderCount", pageBean.getAllRow() + pageBean1.getAllRow()); ///当前配送订单的数量
				   returnMap.put("orderCount", goodsSellRecord.size() + goodsSellRecord1.size());
				  returnMap.put("name", name);//名称
				  returnMap.put("add", map.get("address"));
				  MapList.add(returnMap);

			   }
			   }   //加入坐标非空判断
			   }
			else{
				System.out.print("false  坐标问题");

			}
			}
			 model.put("list", MapList);
		model.put("success",true);
		 }

		}
		return model;
	}
	
	
	//ת/转单详情
	@RequestMapping(value="transOrderdetail",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap transOrderInfo(@RequestParam(value="orderCode",required=false) String orderCode ,String token) throws UnsupportedEncodingException{
		//id定单id
		ModelMap model= new ModelMap();
		DecimalFormat obj = new DecimalFormat(".0");
		RunfastShopper shopper=super.getLoginShopper(token);

		if(shopper!=null&&orderCode!=null){
		RunfastTransorder t=transOrderService.findByorderCode1(orderCode);
		//t.getaskShopperId();///发起转单请求的骑手id
		if(t!=null){
			if(!(t.getStatus() == 1 || t.getStatus() == 2)){
				//转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
				model.put("comment", t.getComment());//转单原因
				model.put("takeType", t.getTaketype());///拿货方式
				com.runfast.paotui.dao.model.RunfastShopper sop=shopperService.get(t.getResshopperid());//获取配送员信息
				if(sop!=null){
		//		mp.clear();
					model.put("name", sop.getName());///转单名称
					model.put("phone", sop.getMunber());///电话
					List<Map<String, Object>> addr= MyUtil.getAdd(Double.parseDouble(sop.getLongitude()),Double.parseDouble(sop.getLatitude()),1);//获取配送员信息获得百度位置信息
//					System.out.print("addr");
					model.put("shopaddr", addr);
					model.put("latitude", sop.getLatitude());
					model.put("longitude", sop.getLongitude());
					RunfastGoodsSellRecord gr =goodsSellRecordService.findByOrderCode(t.getOrdercode()); ///订单信息
					Double shopdis=MyUtil.getDistance(Double.parseDouble(sop.getLongitude()), Double.parseDouble(sop.getLatitude()), Double.parseDouble(gr.getBusinessaddresslng()), Double.parseDouble(gr.getBusinessaddresslat()));
					Double bussinessanduser=MyUtil.getDistance(Double.parseDouble(gr.getUseraddresslng()), Double.parseDouble(gr.getUseraddresslat()), Double.parseDouble(gr.getBusinessaddresslng()), Double.parseDouble(gr.getBusinessaddresslat()));
					model.put("bussinessanduser",bussinessanduser);
					model.put("shopdis", obj.format(shopdis));///骑手到商家距离
					Map<String,Object> loc = MyUtil.getGDlocFromBD( gr.getBusinessaddresslng(), gr.getBusinessaddresslat()) ;
					Map<String,Object> userLoc = MyUtil.getGDlocFromBD( gr.getUseraddresslng(), gr.getUseraddresslat()) ;
					//System.out.println("addr = "+ gr.getUserAddress() + gr.getAddress() );
					if(userLoc != null&&userLoc.size()>0){
						
						gr.setUseraddresslat(userLoc.get("lat").toString());
						gr.setUseraddresslng(userLoc.get("lng").toString());
//						System.out.println("设置好坐标lat" + gr.getBusinessAddressLat() +"lng = " + gr.getBusinessAddressLng());
						
					}
					
					if(loc != null&&loc.size()>0){
						
						gr.setBusinessaddresslat(loc.get("lat").toString());
						gr.setBusinessaddresslng(loc.get("lng").toString());

						
					}
					 
					else{
						LOG.info("百度坐标转高德坐标失败");
					}
					//把商家的坐标转换成高德的坐标
					
					model.put("success", true);
					model.put("msg", "查看成功");
					if(gr!=null){
					//	String str=JSON.toJSONString(gr);

			//			this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
						amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
						model.put("GoodsSellRecord", gr);
						List<RunfastGoodsSellChildren> gsc=  goodsSellRecordChildrenService.findByOrderCode(gr.getOrdercode());// 外卖商品订单记录子类
						model.put("gsc", gsc);
					}
				}
			}
			else
			{
				model.put("success", false);
				model.put("msg", "你已经处理过该转单请求");
			}
		}else{
			model.put("success", false);
			model.put("msg", "订单号为空或者登陆信息为空");
		}
	//	model.put("list", MapList);
		}
		return model;
	}
	
	
	//骑手转单回复
	@RequestMapping(value="transOrderResp",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap ordersingle1(@RequestParam(value="orderCode",required=false) String orderCode,  //定单id
			@RequestParam(value="status",required=false) Integer status,String token
			){


		//1.同意转单， 转单成功
		//	 1)执行操作转单操作,修改数据
		//	2)通知双方转单成功
		//2.拒绝转单，转单
		//	1)不做任何操作，通知给发起转单的骑手。
		ModelMap model= new ModelMap();
	//	boolean  blg=false;
		RunfastShopper sp=super.getLoginShopper(token);
	//	RunfastShopper shopper=shopperService.get(super.getLoginShopper(token).getId());
		if(sp!=null&&orderCode!=null){
		RunfastTransorder t=transOrderService.findByorderCode1(orderCode);//通过订单号查询转单情况

		if(t!=null&&t.getAskshopperid()!=null&&t.getResshopperid()!=null&&t.getStatus()!=null){

			if(status!=null&&status==1){

				//同意转单
				t.setStatus(1);//转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
				transOrderService.updateByPrimaryKey(t);

				RunfastGoodsSellRecord gr = goodsSellRecordService.findByOrderCode(t.getOrdercode());//通过定单号查询外卖订单情况
			//	 TransOrder to = transOrderService.findByorderCode(orderCode);
					RunfastShopper shop=shopperService.get(t.getResshopperid());///响应者 通过转单中获得骑手消息

					if(gr!=null&&t!=null&&shop!=null){
						//来我这取
						gr.setOldshopper(gr.getShopper());//把原配送员 改成old
						gr.setOldshopperid(gr.getShopperid());//设置原配送员的ID
						gr.setOldshoppermobile(gr.getShoppermobile());//设置原配送员的电话

						//设置成新的配送员信息
						gr.setShopper(sp.getName());//通过登陸查询骑手信息，设置shopper的名字
						gr.setShopperid(sp.getId());//设置骑手 的id
						gr.setShoppermobile(sp.getMunber());//设置骑手 的电话
//						System.out.println("修改订单信息成功！");
				       if(t.getComment()!=null){
				    	   gr.setContent1(t.getComment());//转单原因
			            }
						 goodsSellRecordService.update(gr);// 更新外卖商品订单
						//写入操作信息表----------------------
						 RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();//   外卖商品配送状态
						  goodsSellOutStatus.setBusinessid(gr.getBusinessid());////通过定单号查询外卖订单情况中获得商家ID
						  goodsSellOutStatus.setBusinessname(gr.getBusinessname());//通过定单号查询外卖订单情况中获得商家名字
						  goodsSellOutStatus.setCreatetime(new Date());//设置状态更改时间
						  goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());//通过定单号查询外卖订单情况获得订单号
						  goodsSellOutStatus.setGoodssellrecordid(gr.getId());//通过定单号查询外卖订单情况获得id
						  goodsSellOutStatus.setOperationid(super.getLoginShopper(token).getId());//设置登陸时骑手的ID
						  goodsSellOutStatus.setOperationname(shop.getName());//设置骑手的名字
						  goodsSellOutStatus.setSort(gr.getStatus());//通过定单号查询外卖订单情况 获得订单进行的状态
						  goodsSellOutStatus.setStatstr(gr.getOldshopper() +"转单给"+ gr.getShopper());//设置转单详情
						  goodsSellOutStatus.setType(2);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
						goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
//						  RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);//   外卖商品配送状态
//						//// sort   订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
//						  if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(8))||goodsSellOut.getSort()==null){
//						  	//当配送不为空，当订单状态为完成时
//							//保存订单信息
//						  }else{
//							  LOG.info("骑手转单写入操作记录失败。订单号：" + gr.getOrdercode());
//						  }

						//写入操作信息表完毕
				//		String str=JSON.toJSONString(gr);

					//	this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
						amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
						 model.put("success", true);
						 model.put("msg", "转单成功!");
					 }else{

						 model.put("success",false);
						 model.put("msg", "转单信息更改失败");
					 }
				RunfastShopper sop=shopperService.get(t.getResshopperid());
				//通知转单申请者
				if(sop!=null&&sop.getPushType()!=null&&sop.getAlias()!=null){
					//同意转单请求
                  System.out.print("同意转单申请");
				/*	if(sop.getPushType()==3&&sop.getBptype()==null||sop.getBptype()==0){
						 Map<String,String> parms = new HashMap<>();  
				//	     parms.put("Id", t.getId().toString());
					     parms.put("Content", "同意转单请求");
					     parms.put("title", "同意转单");
					     parms.put("orderCode",orderCode);
					     parms.put("sound","agree.caf");
					     try { 
				                PushPayload data = MsgPushUtils.sendAndroidAndIosMessageWithAlias("10",parms,"同意转单", sp.getName() +"同意转单请求", sop.getAlias());//发送给安卓iod特定用户
				                MsgPushUtils.sendPush1(data);
				            } catch (APIConnectionException e) {
				                LOG.error("Connection error. Should retry later. ", e);
				            } catch (APIRequestException e) {
				            	LOG.error("Error response from JPush server. Should review and fix it. ", e);
				            	LOG.info("HTTP Status: " + e.getStatus());
				            	LOG.info("Error Code: " + e.getErrorCode());
				            	LOG.info("Error Message: " + e.getErrorMessage());
				            }
					}else if(sop.getBptype()==1&&sop.getPushType()==3){
						try { 
							 Map<String,String> parms = new HashMap<>();  
								//	     parms.put("Id", t.getId().toString());
									     parms.put("Content", "同意转单请求");
									     parms.put("title", "同意转单");
									     parms.put("orderCode",orderCode);
									     parms.put("sound","agree.caf");
							 PushPayload data1 = MsgPushUtils.sendAndroidAndIosMessageWithAlias("10",parms,"同意转单", sp.getName() +"同意转单请求", sop.getAlias());//发送给安卓iod特定用户
							 MsgPushUtils.sendPush1(data1);
			                PushPayload data = MsgPushUtils.buildPushObjectIosTagAndAlertWithExtrasAndMessage("10", sop.getAlias(), sop.getAlias(), 1, "agree.caf",sp.getName() + "同意转单"+orderCode, "同意转单请求");
			                MsgPushUtils.sendPush1(data);
			            } catch (APIConnectionException e) {
			                LOG.error("Connection error. Should retry later. ", e);
			            } catch (APIRequestException e) {
			            	LOG.error("Error response from JPush server. Should review and fix it. ", e);
			            	LOG.info("HTTP Status: " + e.getStatus());
			            	LOG.info("Error Code: " + e.getErrorCode());
			            	LOG.info("Error Message: " + e.getErrorMessage());
			            }
					}	*/
				}
				System.out.println("************************************************************1");
			//	String str=JSON.toJSONString(gr);

		//		this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
				amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
				model.put("msg", "同意转单状态更改成功");
				model.put("success", true);






				//通知原骑手转单
				}else if(status == 2){
					t.setStatus(2);//转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
					transOrderService.updateByPrimaryKey(t);

					model.put("msg", "拒绝转单申请");
					model.put("success", true);
					RunfastShopper sp1=shopperService.get(t.getAskshopperid());////发起转单请求的骑手id
					RunfastGoodsSellRecord gs = goodsSellRecordService.findByOrderCode(t.getOrdercode());//外卖商品信息
					if(sp1!=null&&sp1.getPushType()!=null&&sp1.getAlias()!=null){///同意转单请求
						if(sp1.getPushType()==3&&sp1.getBptype()==null||sp1.getBptype()==0&&!sp1.getAlias().isEmpty()){
							System.out.println(gs.getStatus()+"a##################################################");
							//push类型对应的用户标识类型 //bptype 0或空  Android用户  1 i
							// os用户
							DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String date1=dateFormat.format(gs.getCreatetime());
							 Map<String,String> parms = new HashMap<>();  
						     parms.put("Id", t.getOrderid().toString());//订单id
						     parms.put("Content", sp.getName() + "已拒绝转单申请");//通过登陸骑手发出拒绝申请
						     parms.put("title", sp.getName() + "拒绝转单请求");
						     parms.put("orderCode",gs.getOrdercode());//定单号
						     parms.put("businessName", gs.getBusinessname());//外卖商品规格信息获得商家的名称
						     parms.put("businessAddr", gs.getBusinessaddr());//外卖商品规格信息获得商家的地址
						     parms.put("userAddress", gs.getUseraddress());//用户地址
						 //    parms.put("createTime", gs.getCreatetime().toString());//下单时间
							parms.put("createTime", date1);//下单时间

						     parms.put("sound","refuse.caf");
						     MsgPushUtils.sendtoAndroid("10",parms,sp.getName() + "已拒绝转单申请"+gs.getOrdercode(), sp.getName() + "拒绝转单请求", sp1.getAlias());//发送给安卓iod特定用户
					         
						}else if(sp1.getBptype()==1&&sp1.getPushType()==3){
							//Bptype 0或空  Android用户  1 ios用户 //PushType push类型对应的用户标识类型
							DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String date2=dateFormat.format(gs.getCreatetime());
								 Map<String,String> parms = new HashMap<>();  
							     parms.put("Id", t.getOrderid().toString());///订单id
							     parms.put("orderCode",gs.getOrdercode());
							     parms.put("businessName", gs.getBusinessname());
							     parms.put("businessAddr", gs.getBusinessaddr());
							     parms.put("userAddress", gs.getUseraddress());
							parms.put("createTime", date2);//下单时间
							//     parms.put("createTime", gs.getCreatetime().toString());
						//	System.out.println(gs.getCreatetime()+"*****************************************************");
							     parms.put("sound","refuse.caf");
							     MsgPushUtils.sendtoAndroid("10",parms,sp.getName() + "已拒绝转单申请"+gs.getOrdercode(), sp.getName() + "拒绝转单请求", sp1.getAlias());//将发起转单请求的骑手id 拒绝请求发送给安卓用户
				                 MsgPushUtils.sendtoIOS("10", sp1.getAlias(), sp1.getAlias(), 1, "refuse.caf", sp.getName() + "拒绝转单请求", sp.getName() + "拒绝转单请求");

						}	
				}

				model.put("msg", "拒绝转单申请");
				model.put("success", true);
			}else {

				model.put("msg", "系统错误");
				model.put("success", true);
			}
		}else {
			model.put("msg", "转单成功了");
			model.put("success", true);
		}
		}
		return model;
	}
	
	//ת转单申请
	@RequestMapping(value="transOrderAsk",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap ordertransAsk(@RequestParam(value="orderCode",required=false) String orderCode,
			@RequestParam(value="id",required=false) Integer id,//要转给骑手的ID
			String token,//当前骑手的id
			@RequestParam(value="takeGoodType",required=false) Integer takeGoodType, //0 来我的取  1去商家去取
			@RequestParam(value="comment",required=false) String comment){

		//1，通知要转到的地方。推送给对应的骑手
		//2.写入转单申请数据库
		ModelMap model= new ModelMap();

		RunfastShopper sp=super.getLoginShopper(token);
		RunfastTransorder t = transOrderService.findByorderCode1(orderCode);//转单情况

		if(t == null)
		{
			t=new RunfastTransorder();//重新生成转单
			t.setStatus(-1);//转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
		}
		//只有已经拒绝的 或者是新的才能申请

		if(sp!=null&&id!=null && (t.getStatus() == -1 || t.getStatus() == 2)){
			//转单状态，-1，订单已取消 转单无效   0，发起请求待响应 1，同意转单请求 2，拒绝转单请求
			//当登陸骑手 不为空，要转为另一骑手的ID不为空，拒绝转单时
			//transOrderService.findByorderCode(orderCode);

			RunfastGoodsSellRecord gs=goodsSellRecordService.findByOrderCode(orderCode);// 通过定单号查询  外卖商品规格

			if(gs!=null){
				/*&&gs.getAgree()!=null&&gs.getAgree()==0*/

				if(t.getStatus()==-1){
					//-1，订单已取消 转单无效
				t.setOrdercode(gs.getOrdercode());////转单情况中设置定单号

				t.setOrderid(gs.getId());////转单情况中设置定单id 也就是外卖订单ID
				t.setResshopperid(id);//设置骑手id
				t.setAskshopperid(sp.getId());////响应请求的骑手id
				t.setTaketype(takeGoodType);//拿货方式，  0，去发起骑手那取， 1.去商家取
				t.setStatus(0);//0，发起请求待响应
				t.setComment(comment);// 备注
				transOrderService.insert(t);///保存到数据库
				}else{
				//	t.setorderCode(orderCode);
				//	t.setorderId(gs.getId());
					System.out.print(id+"aid"+sp.getId()+"spid"+takeGoodType+"a"+comment);
					t.setResshopperid(id);
					t.setAskshopperid(sp.getId());
					t.setTaketype(takeGoodType);
					t.setStatus(0);
					t.setComment(comment);//备注
					transOrderService.updateByPrimaryKey(t);
				}
				com.runfast.paotui.dao.model.RunfastShopper shp=shopperService.get(id);
				///发送通知
				if(shp!=null&&shp.getPushType()!=null&&shp.getAlias()!=null){//发送转单请求
					if(shp.getPushType()==3&&shp.getBptype()==null||shp.getBptype()==0){
						//push类型对应的用户标识类型推送类型0百度推送1小米推送2华为推送
						// bptype;//0或空  Android用户  1 ios用户
						 Map<String,String> parms = new HashMap<>();  
			//		     parms.put("Id", t.getorderId().toString());
					     parms.put("Content", "转单请求");
					     parms.put("title", "转单请求提醒");
					     parms.put("orderCode", gs.getOrdercode());
					     parms.put("businessAddr", gs.getBusinessaddr());
					     parms.put("createTime", gs.getCreatetime().toString());
				//	     parms.put("bptype",acc.getBptype().toString());
					     parms.put("sound","request.caf");
					 
				         MsgPushUtils.sendtoAndroid("10",parms,"转单请求", "转单请求提醒", shp.getAlias());//发送给安卓iod特定用户
				                
				          
					}else if(shp.getBptype()==1&&shp.getPushType()==3){
			                MsgPushUtils.sendtoIOS("10", shp.getAlias(), shp.getAlias(), 1, "request.caf", "收到"+shp.getName() +"的转单请求订单号为:"+gs.getOrdercode(), "转单请求");
			         
					}	
					
				}

				model.put("msg", "成功");
				model.put("success", true);
			}else {
				model.put("msg", "没有转单申请");
				model.put("success", false);
			}
			}else{
				model.put("msg", "转单申请已经提交不能重复转单");
				model.put("success", false);
			}
		return model;
	}
	
	
	/**
	 *同意转单
	 */
	@RequestMapping(value="ordersingle",method=RequestMethod.POST)//��֤
	public @ResponseBody ModelMap ordersingle1(@RequestParam(value="orderCode",required=false) String orderCode,
	//		@RequestParam(value="id",required=false) Integer id,////要转给骑手的id
	//		@RequestParam(value="takeGoodType",required=false) Integer takeGoodType,//0来我这取货1，去商家取货
	//		@RequestParam(value="content",required=false) String content,
											   String token){
		
		ModelMap model= new ModelMap();

		if(super.getLoginShopper(token)!=null&&orderCode!=null){
			//骑手信息订单编号不能为空
			RunfastGoodsSellRecord gr = goodsSellRecordService.findByShopperIdAndOrderCode1(super.getLoginShopper(token).getId(),orderCode);	//查找原配送员的订单信息
			RunfastTransorder to = transOrderService.findByorderCode1(orderCode);
				RunfastShopper shop=shopperService.get(to.getResshopperid());//响应者
				RunfastShopper shop1=shopperService.get(to.getAskshopperid());//发起者
				List<RunfastShopper> slist=shopperService.findBuAgentId(gr.getAgentid(), gr.getTeamid());
				if(to.getTaketype()==0){
					///来我这取
					   gr.setShopper(shop.getUserName());
					   gr.setShopperid(to.getResshopperid());
					   gr.setShoppermobile(shop.getMunber());
					   gr.setOldshopper(gr.getOldshopper());
					   gr.setOldshopperid(to.getAskshopperid());
					   gr.setOldshoppermobile(gr.getOldshoppermobile());
				       if(to.getComment()!=null){
			        gr.setContent1(to.getComment());///转单原因
			            }
				 goodsSellRecordService.update(gr);

					model.put("msg", "转单成功");
					model.put("success", true);
				 }
				else if(to.getTaketype()==1){
					   gr.setShopper(shop.getUserName());
					   gr.setShopperid(to.getResshopperid());
					   gr.setShoppermobile(shop.getMunber());
					   gr.setOldshopper(gr.getOldshopper());
					   gr.setOldshopperid(to.getAskshopperid());
					   gr.setOldshoppermobile(gr.getOldshoppermobile());
					   gr.setLessps(gr.getLessps());
					       if(to.getComment()!=null){
				        gr.setContent1(to.getComment());////转单原因
				            }
					 goodsSellRecordService.update(gr);
				//	 goodsSellRecordService.delete(gr.getId());

					model.put("msg", "转单成功了");
					model.put("success", true);
				}

			model.put("msg", "转单成功");
			model.put("success", true);
			  }

		return model;
	}
	/**
	 * ǩ 签到
	 */
	@RequestMapping(value="shopperSign",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap shopperSign(@RequestParam(value="id",required=false) Integer id,String token){
		//id 为骑手外卖订单id
		ModelMap model = new ModelMap();
		String msg ="参数错误！";
		boolean isSuccess = false;
		if(super.getLoginShopper(token)!=null&&id!=null){
				RunfastShopper shopper=super.getLoginShopper(token);
				RunfastGoodsSellRecord gr = goodsSellRecordService.get(id); //通过骑手外卖商品订单
				if(gr!=null&&gr.getStatus()!=null&&super.getLoginShopper(token).getId().equals(gr.getShopperid())&&gr.getStatus()>1){
					// 2：商家接单


					//订单状态操作记录
					  RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();	//订单状态操作记录
					  goodsSellOutStatus.setBusinessid(gr.getBusinessid());//商家id
					  goodsSellOutStatus.setBusinessname(gr.getBusinessname());//设置商家名字
					  goodsSellOutStatus.setCreatetime(new Date());//设置订单状态时间
					  goodsSellOutStatus.setGoodssellrecordcode(gr.getOrdercode());//设置定单号
					  goodsSellOutStatus.setGoodssellrecordid(gr.getId());//外卖商品订单id
					  goodsSellOutStatus.setOperationid(super.getLoginShopper(token).getId());//设置登陸骑手id
					  goodsSellOutStatus.setOperationname(shopper.getName());
					  goodsSellOutStatus.setSort(2);//9骑手到达商家处
					  goodsSellOutStatus.setStatstr("骑手到店取货中");
					  goodsSellOutStatus.setType(2);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

					  RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);//  外卖商品配送状态
					goodsSellOutStatusService.insertSelective(goodsSellOutStatus);
					/*  if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(9))){
						  //    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，9:骑手到达
					  	////  外卖商品配送状态为空时，操作人类型不为空时，骑手没有到达时


					  }*/
					gr.setShoppersign(1);//骑手到达签到
					gr.setStatus(3);
					gr.setStatstr("骑手到达商家处已签到");
					goodsSellRecordService.update(gr);//更新外卖商品信息
				//	String str=JSON.toJSONString(gr);

			//		this.rabbitTemplate.convertAndSend("waimai", JSON.toJSONString(gr)); //保存在队列
					amqpTemplate.convertAndSend("wm_shopper_order_exchange", "", JSON.toJSONString(gr));
					msg = "签到成功!";
					isSuccess = true;
			}else if(gr.getStatus()==1){
					model.put("success",false);
				msg ="商家未接单，请先提醒商家接单！";

			}else {
					msg = "签到异常，可能商家没接单!";
					isSuccess = true;
				}
			}

		model.put("msg", msg);
		model.put("success", isSuccess);
		return model;
	}
	//骑手上下班切换
	@RequestMapping(value="working",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap working(@RequestParam(value="wrkin",required=false)String wrkin,String token){ //骑手id
		ModelMap model = new ModelMap();
		 RunfastShopper shopper = super.getLoginShopper(token);
		  if(shopper!=null){
			  RunfastShopper sh   = shopperService.get(shopper.getId());
		      if(sh!=null){
		    	  int cc = Integer.parseInt(wrkin);//不为空，就说明在上班
		    	  sh.setWorking(cc);//设置上班状态
		    	  shopperService.update(sh);//更新上班状态，
		//		  String str=JSON.toJSONString(sh);
				  //					System.out.println(shopper.getLatitude()+"纬度&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+shopper.getLongitude());
				  //				System.out.println(str+"更新后的结果");
			//	  this.rabbitTemplate.convertAndSend("hellowo",JSON.toJSONString(sh)); //保存在队列
				  amqpTemplate.convertAndSend("shopper_exchange", "", JSON.toJSONString(sh));
		    	  model.put("success", true);
		    	  model.put("msg", "̬状态修改成功");

		      }
		  
		  }else{
			  model.put("msg", "请先登录");
		  }
		return model;
	}

	//骑手是否有任务未完成
	@RequestMapping(value="isorder",method=RequestMethod.POST)//验证
	public @ResponseBody ModelMap isorder(String token){
		ModelMap model = new ModelMap();
		 RunfastShopper shopper = super.getLoginShopper(token);
		  if(shopper!=null){
			  List<RunfastGoodsSellRecord> list1=  goodsSellRecordService.findById(shopper.getId());//外卖商品规格
			  List<Order> list2=orderService.findByShopperid(shopper.getId());//跑腿商品规格

			  if((list1!=null||list2!=null)&&list1.size()>0||list2.size()>0){
			  		model.put("success",true);
				  model.put("isorder", "还有未完成的任务");
			  }else{
			  		model.put("success",false);
				  model.put("isorder", "0"); 
			  }
		  }
		return model;
	}
	//@Component

@PostMapping("waimaiordermsg")
	public @ResponseBody ModelMap waimaiordermsg(Integer id,String token) {

	ModelMap model = new ModelMap();
	RunfastGoodsSellRecord runfastGoodsSellRecord = goodsSellRecordService.get(id);

	RunfastShopper sp = super.getLoginShopper(token);

	if (null != runfastGoodsSellRecord) {
	List<RunfastGoodsSellChildren> grclist = goodsSellRecordChildrenService.findByOrderCode(runfastGoodsSellRecord.getOrdercode());///查询订单子选项

		if (grclist != null && grclist.size() > 0) {
			for (RunfastGoodsSellChildren s:grclist){
				com.runfast.paotui.dao.model.RunfastCuser runfastCuser=cuserService.get(s.getUserid());
				runfastGoodsSellRecord.setOrdercode(s.getOrdercode());
				runfastGoodsSellRecord.setGender(runfastCuser.getGender());
			}

			model.put("GoodsSellRecordChildren", grclist);


		}
		runfastGoodsSellRecord = MyUtil.replaceTag(runfastGoodsSellRecord); //骑手的坐标定点
		RunfastShopper sp1=shopperService.get(sp.getId());

		//GoodsSellRecord gr =goodsSellRecordService.findByOrderCode(orderCode);  //订单信息
		Map<String, Object> loc = MyUtil.getGDlocFromBD(runfastGoodsSellRecord.getBusinessaddresslng(), runfastGoodsSellRecord.getBusinessaddresslat());//设置商家的经度，纬度
		Map<String, Object> userLoc = MyUtil.getGDlocFromBD(runfastGoodsSellRecord.getUseraddresslng(), runfastGoodsSellRecord.getUseraddresslat());//用户的经度，纬度


		if (userLoc != null && userLoc.size() > 0) {

			runfastGoodsSellRecord.setUseraddresslat(userLoc.get("lat").toString());
			runfastGoodsSellRecord.setUseraddresslng(userLoc.get("lng").toString());
		} else {
			System.out.print("转换坐标失败");
		}

		if (loc != null && loc.size() > 0) {

			runfastGoodsSellRecord.setBusinessaddresslat(loc.get("lat").toString());
			runfastGoodsSellRecord.setBusinessaddresslng(loc.get("lng").toString());
			System.out.println("设置好坐标lat" + runfastGoodsSellRecord.getBusinessaddresslat() + "lng = " + runfastGoodsSellRecord.getBusinessaddresslng());

		} else {
			//LOG.info("百度坐标转高德坐标失败");
		}//把商家的坐标转换成高德的坐标

		if (sp.getLongitude() != null && sp.getLatitude() != null && runfastGoodsSellRecord.getBusinessaddresslng() != null && runfastGoodsSellRecord.getBusinessaddresslat() != null) {
			Double shopdis = MyUtil.getDistance(Double.parseDouble(sp1.getLongitude()), Double.parseDouble(sp1.getLatitude()), Double.parseDouble(runfastGoodsSellRecord.getBusinessaddresslng()), Double.parseDouble(runfastGoodsSellRecord.getBusinessaddresslat()));
			Double runfastBusinesses1 = MyUtil.getDistance(Double.parseDouble(runfastGoodsSellRecord.getUseraddresslng()), Double.parseDouble(runfastGoodsSellRecord.getUseraddresslat()), Double.parseDouble(runfastGoodsSellRecord.getBusinessaddresslng()), Double.parseDouble(runfastGoodsSellRecord.getBusinessaddresslat()));

			//	RunfastGoodsSellRecord runfastGoodsSellRecord1 = goodsSellRecordService.get(id);
			RunfastGoodsSellRecord runfastGoodsSellRecord1 = goodsSellRecordService.get1(id);  //
			System.out.println(sp.getLatitude()+"#####sp"+sp.getLongitude());
			System.out.println(sp1.getLatitude()+"#####sp1"+sp1.getLongitude());
			System.out.println(runfastGoodsSellRecord.getBusinessaddresslat()+"$$$$"+runfastGoodsSellRecord.getBusinessaddresslng());
			System.out.println(runfastGoodsSellRecord.getUseraddresslat()+"#####"+runfastGoodsSellRecord.getBusinessaddresslng());
			Date disTime=runfastGoodsSellRecord1.getDistime();
			Date createTime=runfastGoodsSellRecord1.getCreatetime();
			Date newdate=new Date();

			long bb=runfastGoodsSellRecord1.getBookTime().getTime()-newdate.getTime();
			long min1=bb/(60*1000);
			runfastGoodsSellRecord1.setDaojiTime(min1);

			//				System.out.print(disTime);
			//				System.out.println(disTime.getTime());
			//				System.out.println(createTime.getTime());
			//		long a=disTime.getMinutes()-createTime.getMinutes();
			if(disTime!=null&&createTime!=null){
				long b=disTime.getTime()-newdate.getTime();
				long min=b/(60*1000);
				model.put("remainMin", min);}

				model.put("shopbdis", shopdis.intValue());//骑手到商家距离

			model.put("waimaiordermsg", runfastGoodsSellRecord1);
			model.put("businessesAndUser", Math.round(runfastBusinesses1));
			model.put("success", true);
		} else {
			model.put("success", false);
			model.put("msg", "系统错误");

		}

		runfastGoodsSellRecord.setDistance(String.valueOf(Math.round(Double.parseDouble(runfastGoodsSellRecord.getDistance()))));

	}

		return model;
}
}
